﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using YY.Common;
using YY.UI.BaseDataSvc;

namespace YY.UI
{
    public partial class OrderFrm : BaseFrm
    {
        /// <summary>
        /// 用户源数据临时变量
        /// </summary>
        IEnumerable<TB_User> users = null;

        /// <summary>
        /// 通用分类数据临时变量
        /// </summary>
        IEnumerable<TB_Options> options = null;

        /// <summary>
        /// 数据表临时变量
        /// </summary>
        DataTable dt = null;

        public OrderFrm()
        {
            InitializeComponent();
            YY.Common.EventCommon.OrderUdDGVEvnt += new YY.Common.EventCommon.UpdateDataGridViewDlgt(updateDgv);
            YY.Common.EventCommon.WorkFlowUdDGVEvnt += new YY.Common.EventCommon.UpdateDataGridViewDlgt(updateWorkflow);
            this.BaseDataProxy = new BaseDataClient();
        }

        #region 委托回调
        private void updateDgv(object o, EventArgs arg)
        {
            if (arg != null)
            {
                CommonEventArg<TB_Order> argObj = (CommonEventArg<TB_Order>)arg;
                if (argObj.OpType == Common.OperateType.Add)
                {
                    search();
                }
                else if (argObj.OpType == Common.OperateType.Update)
                {
                    search();
                }
                else if (argObj.OpType == Common.OperateType.Delete)
                {
                    deleteRow(false, argObj.t.id);
                }
            }
        }

        private void updateWorkflow(object o, EventArgs arg)
        {
            if (arg != null)
            {
                CommonEventArg<TB_Workflow> argObj = (CommonEventArg<TB_Workflow>)arg;
                if (argObj.OpType == Common.OperateType.Update)
                    search();
            }
        }
        #endregion

        /// <summary>
        /// 控件数据初始化
        /// </summary>
        private void init()
        {
            this.dtpEDate.Value = DateTime.Now.AddDays(1);
            this.dtpSDate.Value = DateTime.Now.AddDays(-7);

            Common.BindEnumToComboBox(this.cbBoxOrderStatus, typeof(EnumCommon.OrderStatus), null);
            this.cbBoxOrderStatus.DropDownStyle = ComboBoxStyle.DropDownList;
            Common.BindEnumToComboBox(this.cbBoxCustomsStatus, typeof(EnumCommon.CustomsStatus), null);
            this.cbBoxCustomsStatus.DropDownStyle = ComboBoxStyle.DropDownList;

            Common.ComboBoxBindDatas<TB_User>(this.cbBoxAgent, this.users, "userName", "id");
            //this.cbBoxAgent.DropDownStyle = ComboBoxStyle.DropDownList;
            this.cbBoxAgent.KeyPress += new KeyPressEventHandler(cbBoxUser_KeyPress);

            Common.ComboBoxBindDatas<TB_User>(this.cbBoxOperator, this.users, "userName", "id");
            //this.cbBoxOperator.DropDownStyle = ComboBoxStyle.DropDownList;
            this.cbBoxOperator.KeyPress += new KeyPressEventHandler(cbBoxUser_KeyPress);

            Common.BindOptionsComboBox(this.cbBoxStowageMethod, this.options, EnumCommon.OptionType.装柜形式);
            //this.cbBoxStowageMethod.DropDownStyle = ComboBoxStyle.DropDownList;
            this.cbBoxStowageMethod.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);
        }

        private void OrderFrm_Load(object sender, EventArgs e)
        {

            this.cbBoxOrderStatus.DrawMode = DrawMode.OwnerDrawFixed;
            this.cbBoxOrderStatus.DropDownStyle = ComboBoxStyle.DropDownList;

            this.BaseDataProxy.Open();
            this.options = this.BaseDataProxy.FindOptions(null, null, null);
            this.users = this.BaseDataProxy.FindUsers(null, null);
            initDgvColumns();
            init();
            search();
        }

        /// <summary>
        /// 初始化表格列
        /// </summary>
        private void initDgvColumns()
        {
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;//AutoSize十分影响性能
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "OrderId", "作业单Id", false, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "OrderCode", "作业单号", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "CCode", "提单号", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "ClientName", "委托方", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewCheckBoxColumn(), "IsOffer", "交单", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewCheckBoxColumn(), "IsCheck", "查验", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewCheckBoxColumn(), "IsPass", "放行", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewCheckBoxColumn(), "IsNotice", "通知", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "OrderStatus", "工作状态", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "CustomsStatus", "报关状态", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "ApplyDate", "申报时间", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "BizManName", "业务员", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "AgentName", "客服", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "PassTime", "放行时间", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewCheckBoxColumn(), "DeleteFlag", "取消", true, true, null);
            //Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "CheckOffCode", "核销号", true, true, null);
            //Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "CaseCode", "柜号", true, true, null);
        }

        /// <summary>
        /// 数据搜索
        /// </summary>
        private void search()
        {
            int? agent = null;
            if (this.cbBoxAgent.SelectedItem != null)
                agent = (this.cbBoxAgent.SelectedItem as TB_User).id;

            int? bizMan = null;
            if (this.cbBoxOperator.SelectedItem != null)
                bizMan = (this.cbBoxOperator.SelectedItem as TB_User).id;

            bool? isDrawBack = null;
            if (!string.IsNullOrEmpty(this.cbBoxDrawBack.Text))
                isDrawBack = this.cbBoxDrawBack.Text == "是";

            bool? deleteFlag = null;
            if (!string.IsNullOrEmpty(this.cbBoxDeleteFlag.Text))
                deleteFlag = this.cbBoxDeleteFlag.Text == "取消状态";

            int? stowageMethod = null;
            if (this.cbBoxStowageMethod.SelectedItem != null)
                stowageMethod = (this.cbBoxStowageMethod.SelectedItem as TB_Options).id;

            DateTime dtStart = this.dtpSDate.Value.Date;
            DateTime dtEnd = this.dtpEDate.Value.AddDays(1).Date.AddSeconds(-1);
            if (this.dt != null && this.dt.Rows.Count > 0)
                this.dt.Clear();
            IEnumerable<QOrder> orders = this.BaseDataProxy.FindOrders(deleteFlag, this.txtBoxCode.Text, this.txtBoxCCode.Text, dtStart, dtEnd, this.cbBoxOrderStatus.Text, agent, bizMan, stowageMethod, this.txtBoxClient.Text, isDrawBack, this.cbBoxCustomsStatus.Text, this.txtBoxCheckOffCode.Text, this.txtBoxCaseCode.Text);
            if (orders != null)
                this.dt = orders.ToDataTable();
            this.dataGridView1.SuspendLayout();
            this.dataGridView1.DataSource = this.dt;
            this.dataGridView1.AutoResizeColumns();
            this.dataGridView1.ResumeLayout();
        }

        /// <summary>
        /// 通用分类选择框回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void optionCbBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                ComboBox cbBox = sender as ComboBox;
                EnumCommon.OptionType ot = (EnumCommon.OptionType)cbBox.Tag;
                if (this.options != null)
                {
                    TB_Options[] os = this.options.Where(p => p.type == ot.ToString()).Where(p => p.name.Contains(cbBox.Text) || p.code.Contains(cbBox.Text)).ToArray();
                    Common.ComboBoxMatchOption(cbBox, os, this, ot);
                }
            }
        }

        /// <summary>
        /// 用户选择框回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbBoxUser_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                ComboBox cbBox = sender as ComboBox;
                if (this.users != null)
                {
                    TB_User[] users = this.users.Where(p => p.userName.Contains(cbBox.Text) || p.code.Contains(cbBox.Text)).ToArray();
                    Common.ComboBoxMatchUser(cbBox, users, this);
                }
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            search();
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dataGridView1.CurrentRow != null)
            {
                int id = Convert.ToInt32(this.dataGridView1.CurrentRow.Cells[0].Value);
                EditOrderFrm frm = new EditOrderFrm();
                frm.OrderId = id;
                frm.EditMode = true;
                frm.Show(this);
                //if (!Common.MdiFrmIsOpened(this.MdiParent, frm.Name))
                //{
                //    //frm.MdiParent = this.MdiParent;
                //    frm.Owner = this;
                //    frm.Show();                    
                //}
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //EditOrderFrm frm = new EditOrderFrm();
            //frm.ShowDialog(this);
            EditOrderFrm frm = new EditOrderFrm();
            frm.Show(this);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.CurrentRow != null)
                deleteRow(true, Convert.ToInt32(this.dataGridView1.CurrentRow.Cells[0].Value));
        }

        /// <summary>
        /// 数据源删除选中行
        /// </summary>
        private void deleteRow(bool serverDelete, int id)
        {
            if (serverDelete)
            {
                if (MessageBox.Show("确认取消该工作单吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    if (Common.BIZ_OrderIsSubmit(id))
                    {
                        MessageBox.Show("已提交财务审核单据不能修改！");
                        return;
                    }

                    MsgBoolean mb = this.BaseDataProxy.DeleteOrder(id);
                    if (mb == null)
                    {
                        MessageBox.Show("单据取消异常！");
                        return;
                    }
                    if (mb.Ok)
                        MessageBox.Show("单据已被设置取消状态！");
                    else
                    {
                        MessageBox.Show(mb.Msg);
                        return;
                    }
                }
                else
                    return;

            }
            //DataRow[] drs = this.dt.Select("OrderId=" + id.ToString());
            //foreach (DataRow dr in drs)
            //    this.dt.Rows.Remove(dr);
            //this.dt.AcceptChanges();
            search();
        }

        private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }

        private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(sender);
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            base.OnFormClosed(e);
            YY.Common.EventCommon.OrderUdDGVEvnt -= new YY.Common.EventCommon.UpdateDataGridViewDlgt(updateDgv);
            YY.Common.EventCommon.WorkFlowUdDGVEvnt -= new YY.Common.EventCommon.UpdateDataGridViewDlgt(updateWorkflow);
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            this.cbBoxAgent.SelectedIndex = -1;
            this.cbBoxCustomsStatus.SelectedIndex = -1;
            this.cbBoxDrawBack.SelectedIndex = -1;
            //this.cbBoxKdsk.SelectedIndex = -1;
            this.cbBoxOperator.SelectedIndex = -1;
            this.cbBoxOrderStatus.SelectedIndex = -1;
            this.cbBoxStowageMethod.SelectedIndex = -1;
            this.cbBoxDeleteFlag.SelectedIndex = -1;
            this.txtBoxCCode.Text = null;
            this.txtBoxClient.Text = null;
            this.txtBoxCode.Text = null;
        }

        Color getStatuColor(string status)
        {
            //if (status == EnumCommon.OrderStatus.订舱录入.ToString())
            //{
            //    return Color.LightCyan;
            //}
            if (status == EnumCommon.OrderStatus.接单确认.ToString())
            {
                return Color.Aquamarine;
            }
            else if (status == EnumCommon.OrderStatus.操作完成.ToString())
            {
                return Color.DodgerBlue;
            }
            else if (status == EnumCommon.OrderStatus.财务审核.ToString())
            {
                return Color.MistyRose;
            }
            else if (status == EnumCommon.OrderStatus.待出账单.ToString())
            {
                return Color.LightSalmon;
            }
            else if (status == EnumCommon.OrderStatus.已出账单.ToString())
            {
                return Color.OrangeRed;
            }
            else if (status == EnumCommon.OrderStatus.已收款.ToString())
            {
                return Color.LawnGreen;
            }
            else if (status == EnumCommon.OrderStatus.取消.ToString())
                return Color.Gray;
            else
                return SystemColors.Window;
        }

        private void cbBoxOrderStatus_DrawItem(object sender, DrawItemEventArgs e)
        {
            
            //判断是否需要重绘
            if (e.Index >= 0)
            {
                ComboBox cBox = (ComboBox)sender;
                string itemKey = cBox.Items[e.Index].ToString();  //子项的颜色名
                Color color = getStatuColor(itemKey);
                SolidBrush brush = new SolidBrush(color); //画笔
                Font font = new Font("宋体", 9);                                                       //字体样式
                Brush brushs = Brushes.Black;

                Rectangle rect = e.Bounds;                                                               //获得需要重绘的区域
                rect.Inflate(-2, -2);                                                                             //缩放一定大小

                Rectangle rectColor = new Rectangle(rect.Location, new Size(20, rect.Height));
                //e.Graphics.FillRectangle(brush, rectColor);                                                  // 填充颜色  
                //绘制选中效果
                SolidBrush brushItem = new SolidBrush(SystemColors.Window);
                if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                    brushItem = new SolidBrush(SystemColors.MenuHighlight); //画笔
                e.Graphics.FillRectangle(brushItem, e.Bounds);

                e.Graphics.FillRectangle(brush, rectColor);//绘制内色
                e.Graphics.DrawRectangle(Pens.Black, rectColor);                                       // 绘制边框  

                //绘制文字
                e.Graphics.DrawString(itemKey, font, brushs, (rect.X + 22), rect.Y);

                
            }

            

        }

        private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (e.RowIndex < this.dataGridView1.Rows.Count)
            {
                try
                {
                    if (Convert.ToBoolean(this.dataGridView1.Rows[e.RowIndex].Cells[14].Value))
                    {
                        this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Gray;
                    }
                    else
                    {
                        object obj = this.dataGridView1.Rows[e.RowIndex].Cells[8].Value;
                        if (obj != null)
                            this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = getStatuColor(obj.ToString());
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

        }
    }
}
